# This file is part of ModularBot.
# Copyright (C) 2005 Pierre Ducroquet (pierre.linux59@wanadoo.fr)

# ModularBot is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# ModularBot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with ModularBot; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import xml.sax.handler
import xml.sax
import copy
import md5

class RightsPlugin (xml.sax.handler.ContentHandler):
	class User:
		def __init__ (self, attributes):
			self.nick = attributes["nick"]
			self.core_admin = False
			if attributes.has_key("core_admin"):
				if attributes["core_admin"] == "true":
					self.core_admin = True
			self.admin = False
			if attributes.has_key("admin"):
				if attributes["admin"] == "true":
					self.admin = True
			self.passwd = ""
			if attributes.has_key("passwd"):
				self.passwd = attributes["passwd"]
			self.rights = []
		
		def add_right (self, attributes):
			self.rights.append(attributes["target"])
	
	def __init__ (self, filename):
		self.filename = filename
	
	def parse (self):
		self.currentUser = None
		self.users = {}
		parser = xml.sax.make_parser()
		parser.setContentHandler(self)
		parser.parse(self.filename)
	
	def startElement(self, name, attributes):
		if name == "user":
			self.currentUser = self.User(attributes)
		elif name == "right":
			self.currentUser.add_right(attributes)
	
	def endElement(self, name):
		if name == "user":
			self.users[self.currentUser.nick] = self.currentUser
			self.currentUser = None
	
	def has_right (self, user, right):
		if self.users.has_key(user):
			return right in self.users[user].rights
		else:
			return False
	
	def is_core_admin (self, user):
		return self.users[user].core_admin

	def is_admin (self, user):
		return self.users[user].admin
	
	def check_passwd (self, user, passwd):
		if self.users.has_key(user):
			passmd5 = md5.new(passwd.strip())
			#if passwd.strip() == self.users[user].passwd:
			if passmd5.hexdigest() == self.users[user].passwd:
				return True
		return False
		